package cn.tedu.tmall.front.mall.dao.repository.impl;

import cn.tedu.tmall.common.pojo.po.MallCategoryCachePO;
import cn.tedu.tmall.common.pojo.vo.MallCategoryTreeVO;
import cn.tedu.tmall.front.mall.dao.repository.ICategoryCacheRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class CategoryCacheRepository implements ICategoryCacheRepository {

    @Autowired
    private RedisTemplate redisTemplate;

    //Map<String,List<MallCategoryTreeVO>>

    @Override
    public void saveCategoryTree(List<MallCategoryTreeVO> mallCategoryTreeVOS) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("ALL",mallCategoryTreeVOS);
    }


    @Override
    public List<MallCategoryTreeVO> getCategoryTree() {
        ValueOperations<String,List<MallCategoryTreeVO>> valueOperations = redisTemplate.opsForValue();
        return valueOperations.get("ALL");
    }

    @Override
    public List<MallCategoryCachePO> getTopCategory() {
        return getCategoryByParentId(0L);
    }

    @Override
    public void saveCategory(List<MallCategoryCachePO> dbTop) {
        saveCategoryByParentId(0L,dbTop);

    }

    @Override
    public List<MallCategoryCachePO> getCategoryByParentId(Long parentId) {
        ListOperations<String, MallCategoryCachePO> listOperations = redisTemplate.opsForList();
        String key = "MALL_CATEGORY_BY_PARENT_ID_" + parentId ;
        return listOperations.range(key,0,-1);
    }

    @Override
    public void saveCategoryByParentId(Long parentId, List<MallCategoryCachePO> dbTop) {
        //思考 用什么样的数据结构?
        // list ?
        // 本身的数据结构是什么样的 单级
        // 更新的时候 什么样的数据时候 增量更新 [北京,山西,河北,上海]
        //   更新山西-新山西 index
        ListOperations listOperations = redisTemplate.opsForList();
        String key = "MALL_CATEGORY_BY_PARENT_ID_" + parentId ;
        for (MallCategoryCachePO categoryPO : dbTop) {
            //todo 时间格式暂时序列化失败,不解决,先设置为空
            listOperations.rightPush(key,categoryPO);
        }
    }
}
